
<template>
	<div class="app-container" v-loading="loading">
		
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入架构名称" clearable @keyup.enter="handleQuery"/>
					</el-col>
					<el-col :span="6">
						<el-button :loading="loading" type="primary" @click="handleQuery"><template
								#icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :columns="false"></FilterColumn>
			</div>
		</div>
		

		<el-card shadow="never" size="small">
			<div class="action-row">
					<el-button v-hasPerm="['Department/save']"  @click="openDialog()" type="primary" plain><template #icon><i-ep-plus /></template>新增</el-button>
			</div>
			<el-table
					v-loading="loading"
					:data="departmentList"
					row-key="id"
					default-expand-all
					border
					size="small"
					@row-click="onRowClick">
					 <el-table-column type="index" label="序号" align="center" width="80" />
				<el-table-column label="架构名称" min-width="200">
					<template #default="scope">
						<svg-icon :icon-class="scope.row.type == 1 ? 'homepage' : 'tree'"/>
						{{ scope.row.name }}
					</template>
				</el-table-column>

				<el-table-column label="负责人" align="center" width="120">
					<template #default="scope">
						<text v-if="scope.row.leader">{{ scope.row.leader.name }}</text>
					</template>
				</el-table-column>

				<el-table-column label="类型" align="center" width="80">
					<template #default="scope">
						<el-tag v-if="scope.row.type == 1">公司</el-tag>
						<el-tag v-if="scope.row.type == 2" type="success"
						>部门
						</el-tag
						>
					</template>
				</el-table-column>

				<el-table-column label="排序" align="center" width="80" prop="sort"/>

				<el-table-column fixed="right" align="center" label="操作" width="300">
					<template #default="scope">
						<el-button
								v-hasPerm="['Department/save']"
								type="success"
								link
								size="small"
								@click.stop="openDialog(scope.row.id)"
						>
							<template #icon>
								<i-ep-plus/>
							</template>
							新增
						</el-button>

						<el-button
								v-hasPerm="['Department/update']"
								type="primary"
								link
								size="small"
								@click.stop="openDialog(undefined, scope.row.id)"
						>
							<template #icon>
								<i-ep-edit/>
							</template>
							编辑
						</el-button>
						<el-button
								v-hasPerm="['DepartmentLeader']"
								type="warning"
								link
								size="small"
								@click.stop="openUserDialog(scope.row.id, scope.row.department_leader)"
						>
							<template #icon>
								<i-ep-UserFilled/>
							</template>
							负责人
						</el-button>
						<el-button
								v-hasPerm="['Department/delete']"
								type="danger"
								link
								size="small"
								@click.stop="handleDelete(scope.row.id)"
						>
							<template #icon>
								<i-ep-delete/>
							</template>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-dialog
				v-model="dialog.visible"
				:title="dialog.title"
				destroy-on-close
				append-to-body
				width="750px"
				@close="closeDialog"
		>
			<el-form
					ref="departmentFormRef"
					:model="formData"
					:rules="rules"
					label-width="100px"
			>
				<el-form-item label="父级架构" prop="parentid">
					<el-tree-select
							v-model="formData.parentid"
							placeholder="选择上级架构"
							:data="departmentOptions"
							:props="departmentProps"
							filterable
							check-strictly
							:render-after-expand="false"
							:default-expand-all="true"
					/>
				</el-form-item>

				<el-form-item label="架构名称" prop="name">
					<el-input v-model="formData.name" placeholder="请输入架构名称"/>
				</el-form-item>

				<el-form-item label="类型" prop="type">
					<el-radio-group v-model="formData.type">
						<el-radio :label="1">公司</el-radio>
						<el-radio :label="2">部门</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="排序" prop="sort">
					<el-input-number
							v-model="formData.sort"
							style="width: 100px"
							controls-position="right"
							:min="0"
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog
				v-model="userDialog.visible"
				:title="userDialog.title"
				destroy-on-close
				append-to-body
				width="750px"
				@close="closeUserDialog"
		>
			<el-form
					ref="leaderFormRef"
					:model="leaderData"
					:rules="leaderRules"
					label-width="100px"
			>

				<el-form-item label="负责人" prop="uid">
					<el-select
							v-model="leaderData.uid"
							placeholder="请选择部门负责人"
					>
						<el-option
								v-for="item in userOptions"
								:key="item.uid"
								:label="item.name"
								:value="item.uid"
						/>
					</el-select>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitLeaderForm">确 定</el-button>
					<el-button @click="closeUserDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
defineOptions({
	// eslint-disable-next-line vue/no-reserved-component-names
	name: "Department",
	inheritAttrs: false,
});

import {DepartmentQuery, DepartmentForm, DepartmentVO} from "@/api/department/types";
import {
	listDepartment,
	getDepartmentForm,
	listDepartmentOptions,
	addDepartment,
	deleteDepartment,
	updateDepartment,
	updateDepartmentLeader,
} from "@/api/department";
import {
	getUserOptions
} from "@/api/user";

import SvgIcon from "@/components/SvgIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";

const queryFormRef = ref(ElForm);
const departmentFormRef = ref(ElForm);
const leaderFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive<DialogOption>({
	visible: false,
});

const userDialog = reactive<DialogOption>({
	title: "设置部门负责人",
	visible: false,
});

const queryParams = reactive<DepartmentQuery>({});
const departmentList = ref<DepartmentVO[]>([]);

const departmentOptions = ref<any>([]);
const userOptions = ref<any>([]);

const departmentProps = {
	label: 'name',
	children: 'children',
	value: 'id',
}

const formData = reactive<DepartmentForm>({
	parentid: undefined,
	name: "",
	sort: 50,
	type: 1,

});

const rules = reactive({
	parentid: [{required: true, message: "请选择顶级架构", trigger: "blur"}],
	name: [{required: true, message: "请输入架构名称", trigger: "blur"}],
});

const leaderData = reactive({
	id: undefined,
	uid: undefined,
});

const leaderRules = reactive({
	uid: [{required: true, message: "请选择负责人", trigger: "blur"}],
});

// 选择表格的行架构ID
const selectedRowDepartmentId = ref<number | undefined>();

/**
 * 查询
 */
function handleQuery() {
	// 重置父组件
	loading.value = true;
	listDepartment(queryParams)
			.then(({data}) => {
				departmentList.value = data;
			})
			.then(() => {
				loading.value = false;
			});
}

/**
 * 查询重置
 */
function resetQuery() {
	
	handleQuery();
}

/**
 * 行点击事件
 */
function onRowClick(row: DepartmentVO) {
	selectedRowDepartmentId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父架构ID
 * @param menuId 架构ID
 */
function openDialog(parentId?: number, departmentId?: number) {
	listDepartmentOptions()
			.then(({data}) => {
				// departmentOptions.value = data;
				departmentOptions.value =  [{ id: 0, name: "顶级组织架构", children: data }];
			})
			.then(() => {
				dialog.visible = true;
				if (departmentId) {
					dialog.title = "编辑架构";
					getDepartmentForm(departmentId).then(({data}) => {
						Object.assign(formData, data);
					});
				} else {
					dialog.title = "新增架构";
					formData.parentid = parentId;
				}
			});
}

/**
 * 架构保存提交
 */
function submitForm() {
	departmentFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			const departmentId = formData.id;
			if (departmentId) {
				updateDepartment(departmentId, formData).then(() => {
					ElMessage.success("修改成功");
					closeDialog();
					handleQuery();
				});
			} else {
				addDepartment(formData).then(() => {
					ElMessage.success("新增成功");
					closeDialog();
					handleQuery();
				});
			}
		}
	});
}

/**
 * 删除架构
 * @param departmentId 架构ID
 */
function handleDelete(departmentId: number) {
	if (!departmentId) {
		ElMessage.warning("请勾选删除项");
		return false;
	}

	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	})
			.then(() => {
				deleteDepartment(departmentId).then(() => {
					ElMessage.success("删除成功");
					handleQuery();
				});
			})
			.catch(() => ElMessage.info("已取消删除"));
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
	departmentFormRef.value.resetFields();
	departmentFormRef.value.clearValidate();

	formData.id = undefined;
	formData.parentid = undefined;
	formData.sort = 50;
	formData.name = undefined;
	formData.type = 1;

}




/**
 * 打开负责人表单弹窗
 *
 * @param id 部门id
 */
function openUserDialog(id?: number, uid?: number) {
	getUserOptions({'did':id})
			.then(({data}) => {
				userOptions.value = data;
			
			})
			.then(() => {
				leaderData.id = id;
				leaderData.uid = uid ? uid * 1 : undefined;
				userDialog.visible = true;
			});
}

/**
 * 架构保存提交
 */
function submitLeaderForm() {
	leaderFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			updateDepartmentLeader(leaderData.id, leaderData).then(() => {
				ElMessage.success("操作成功");
				closeUserDialog();
				handleQuery();
			});
		}
	});
}

/**
 * 关闭弹窗
 */
function closeUserDialog() {
	userDialog.visible = false;
	resetLeaderForm();
}

/**
 * 重置表单
 */
function resetLeaderForm() {
	leaderFormRef.value.resetFields();
	leaderFormRef.value.clearValidate();

	leaderData.id = undefined;
	leaderData.uid = undefined;
}

onMounted(() => {
	handleQuery();
});
</script>

